<template>
    <div>
        <el-dialog title="新增机构" :visible.sync="dialogVisible" width="500px" :before-close="closeDialog"
            :close-on-click-modal="false" :append-to-body="true">
            <el-form :model="addForm" :rules="rules" ref="refForm" label-width="80px">

                <el-form-item size="small" label="上级机构" prop="parentId">
                    <TreeSelSearch style="width: 100%" ref="refTreeSelSearch" @changeOrgId="changeOrgId">
                    </TreeSelSearch>
                </el-form-item>

                <el-form-item size="small" label="机构属性" prop="type">
                    <el-select clearable v-model="addForm.type" style="width: 100%" placeholder="请选择"
                        @change="onChangeTYpe">
                        <el-option v-for="item in agencyTypeList" :label="item.name" :value="item.id" :key="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item size="small" label="省市区" prop="region" v-if="addForm.type == 3">
                    <!-- <el-cascader v-model="addForm.region" placeholder="请选择省市区" :options="provinceCityAreaData"
                        filterable @change="changeProvinceCityArea" popperClass="multi-choose"
                        :props="{ checkStrictly: true, expandTrigger: 'hover' }" style="width: 100%">
                    </el-cascader> -->

                    <el-cascader v-model="addForm.region" placeholder="请选择省市区" :options="provinceCityAreaData"
                         @change="changeProvinceCityArea" popperClass="multi-choose"
                        :props="{ checkStrictly: true, expandTrigger: 'hover', lazy: true, lazyLoad: loadNode, ...optionProps }"
                        style="width: 100%"></el-cascader>

                </el-form-item>

                <el-form-item size="small" label="机构名称" prop="orgName">
                    <el-input clearable v-model.trim="addForm.orgName" placeholder="请输入" style="width: 100%"
                        oninput="value=value.replace(/\s*/g,'')" @blur="addForm.orgName = $event.target.value"
                        maxlength="20" :disabled="addForm.type == 3">
                    </el-input>
                </el-form-item>

                <!-- <el-form-item size="small" label="地区" prop="streetCode">
                <div style="display: flex; align-items: center">
                  <el-select
                    v-model="addForm.provinceCode"
                    placeholder="省"
                    @change="changprovince"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in provinceList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.cityCode"
                    placeholder="市"
                    @change="changcity"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in cityList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.areaCode"
                    placeholder="区"
                    @change="changarea"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in areaList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <el-select
                    v-model="addForm.streetCode"
                    placeholder="街道"
                    @change="changestreet"
                    style="width: 400px; margin-right: 5px"
                  >
                    <el-option
                      v-for="(item, i) in streetList"
                      :key="i"
                      :label="item.regionName"
                      :value="item.regionCode"
                    >
                    </el-option>
                  </el-select>
                  <i
                    class="iconfont zuobiao"
                    style="font-size: 20px; margin-left: 10px; cursor: pointer"
                    @click="openMap"
                  ></i>
                </div>
              </el-form-item> -->

                <!-- <el-form-item size="small" label="描述" prop="description">
                    <el-input type="textarea" :rows="2" placeholder="请输入" v-model="addForm.description"
                        oninput="value=value.replace(/\s*/g,'')" @blur="addForm.description = $event.target.value"
                        maxlength="30" resize="none" :autosize="{ minRows: 2, maxRows: 5 }">
                    </el-input>
                </el-form-item> -->

            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="closeDialog" class="cancel-button">取 消</el-button>
                <el-button size="small" @click="submit" v-preventReClick="1000" class="confirm-button">确 定</el-button>
            </span>

            <el-dialog width="50%" title="选择地区" :visible.sync="innerVisible" append-to-body
                :close-on-click-modal="false">
                <div class="mapLoc" v-if="isShowMap">
                    <iframe :src="reqUrl" v-if="isShowMap" frameborder="0" class="iframe" seamless
                        scrolling="no"></iframe>
                </div>
            </el-dialog>
        </el-dialog>

    </div>
</template>
<script>
import { reqOrgAdd, reqRegion, reqRegionLevel } from "@api/api.js";
import mixinRules from "./mixins/rules.js";
import { mapState } from "vuex";
import $ from "jquery";
import TreeSelSearch from "@components/TreeSelSearch.vue";
import { provinceCityAreaArray } from "@utils/province-city-area";//省市区数据
import {
    handleTree
} from "@utils/trans-tree";

export default {
    props: ["getLocationInfo", "getAddressflag", "fixedPjtInfo"],
    mixins: [mixinRules],
    components: {
        TreeSelSearch,
    },
    data() {
        return {
            // provinceCityAreaData: provinceCityAreaArray,
            provinceCityAreaData: [],
            optionProps: {
                value: 'regionName',
                label: 'regionName',
                children: 'children'
            },
            provinceList: [],
            cityList: [],
            areaList: [],
            streetList: [],
            communityList: [], //社区
            dialogVisible: false,
            innerVisible: false,
            addForm: {
                parentId: "",
                tenantId: "",
                type: "",
                orgName: "",
                // description: "",
            },
            reqUrl:
                "https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1",
            isShowMap: false,
            LocationInfo: true, //判断是否从地图选的经纬度
            activeNames: ["1", "2"],
            agencyTypeList: [
                {
                    id: 2,
                    name: "基础组织",
                },
                {
                    id: 3,
                    name: "行政区划",
                },
            ],
        };
    },
    computed: {
        ...mapState(["user"]),
    },
    watch: {
        dialogVisible(e) {
            if (e) {
                this.addForm.parentId = this.fixedPjtInfo.id;
                this.$nextTick(async() => {
                  await  this.$refs.refTreeSelSearch.getDataList();
                  await  this.$refs.refTreeSelSearch.getvalue(this.fixedPjtInfo.id);
                    this.getRegion()   // 获取省
                });
            }
        },
    },
    methods: {
        // 获取省
        async getRegion() {
            let res = await reqRegion();
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            let {
                rows
            } = res.data;
            this.provinceCityAreaData = handleTree(
                rows,
                "regionCode",
                "regionLevel",
                "ruralCode"
            );
            this.provinceCityAreaData.forEach((item, index) => {
                if (item.regionLevel == 1) {
                    item.hasChildren = true;// 有下级
                }
            });
        },
        loadNode(node, resolve) {
            // 如果当前节点标记为没有子节点，则不继续加载
            if (node.data && node.data.hasChildren === false) {
                resolve([]); // 没有下级，返回空数组
                return;
            }
            // 如果是根节点，加载省份
            if (node.level === 0) {
                // this.fetchProvinces(resolve);
            }
            // 如果是省节点，加载城市
            else if (node.level === 1) {
                // console.log(node);
                this.fetchCities(node.data.regionCode, resolve);
            }
            // 如果是市节点，加载区县
            else if (node.level === 2) {
                this.fetchCities(node.data.regionCode, resolve);
            } else if (node.level === 3) {
                this.fetchCities(node.data.regionCode, resolve);
            } else if (node.level === 4) {
                resolve([]); // 没有下级，返回空数组
                return;
                // this.fetchCities(node.data.regionCode, resolve);
            }
        },
        fetchCities(provinceId, resolve) {
            reqRegionLevel(provinceId).then((res) => {
                const rows = res.data.rows.map((item) => {
                    // 判断是否有下级，regionLevel 等于 5 表示没有下级
                    if (item.regionLevel == 5) {
                        item.hasChildren = false; // 没有下级
                    } else {
                        item.hasChildren = true; // 有下级
                    }
                    return item;
                });
                resolve(rows); // 将处理好的节点数据返回
            });
        },
        // 省市区获取
        changeProvinceCityArea(val,e) {
            // console.log(val,this.provinceCityAreaData,e);
            this.addForm.orgName = val[val.length - 1];// 获取最后一级数据（区级）
        },
        changeOrgId(instanceId) {
            // console.log(instanceId,'instanceId');
            this.addForm.type = "";
            this.addForm.parentId = instanceId.id;
        },
        getLongitudeLatitude() {
            // var geolocation = new BMap.Geolocation();
            //   geolocation.getCurrentPosition(function (r) {
            //     console.log(r.latitude);
            //     console.log(r.longitude);
            //     })
            //     return;
            // var location_lon = "";
            // var location_lat = ""; // 经度,纬度
            // if (navigator.geolocation) {
            //   navigator.geolocation.getCurrentPosition(function(position) {
            //     console.log(position);
            //     location_lon = position.coords.longitude;
            //     location_lat = position.coords.latitude;
            //     // console.log(location_lon, location_lat, "获取定位");
            //     this.reqUrl=`https://apis.map.qq.com/tools/locpicker?search=1&type=1&key=44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53&referer=精卫安管理系统&policy=1&coord=${location_lon},${location_lat}`
            //   });
            // }
        },
        // // 查询省级行政组织
        // async RegionList() {
        //     const res = await reqRegion();
        //     this.provinceList = res.data.rows;
        // },
        onChangeTYpe(e) {
            this.addForm.orgName = ''
        },
        // 根据省查询市
        // async changprovince(val) {
        //     this.LocationInfo = false;
        //     this.addForm.address = "";
        //     this.cityList = [];
        //     this.addForm.city = "";
        //     this.addForm.cityCode = "";
        //     this.areaList = [];
        //     this.addForm.area = "";
        //     this.addForm.areaCode = "";
        //     this.streetList = [];
        //     this.addForm.street = "";
        //     this.addForm.streetCode = "";
        //     this.communityList = [];
        //     this.addForm.community = "";
        //     this.addForm.communityCode = "";
        //     const res = await reqRegionLevel(val);
        //     this.cityList = res.data.rows;
        //     this.provinceList.forEach((item) => {
        //         if (item.regionCode == val) {
        //             this.addForm.province = item.regionName;
        //             return;
        //         }
        //     });
        // },
        // 根据市查询区
        // async changcity(val) {
        //     this.LocationInfo = false;
        //     this.addForm.address = "";
        //     this.areaList = [];
        //     this.addForm.area = "";
        //     this.addForm.areaCode = "";
        //     this.streetList = [];
        //     this.addForm.street = "";
        //     this.addForm.streetCode = "";
        //     this.communityList = [];
        //     this.addForm.community = "";
        //     this.addForm.communityCode = "";
        //     const res = await reqRegionLevel(val);
        //     this.areaList = res.data.rows;
        //     this.cityList.forEach((item) => {
        //         if (item.regionCode == val) {
        //             this.addForm.city = item.regionName;
        //             return;
        //         }
        //     });
        // },
        // 根据区查询街道
        // async changarea(val) {
        //     this.LocationInfo = false;
        //     this.addForm.address = "";
        //     this.streetList = [];
        //     this.addForm.street = "";
        //     this.addForm.streetCode = "";
        //     this.communityList = [];
        //     this.addForm.community = "";
        //     this.addForm.communityCode = "";
        //     const res = await reqRegionLevel(val);
        //     this.streetList = res.data.rows;
        //     this.areaList.forEach((item) => {
        //         if (item.regionCode == val) {
        //             this.addForm.area = item.regionName;
        //             return;
        //         }
        //     });
        // },
        // 街道名字赋值
        // async changestreet(val) {
        //     this.communityList = [];
        //     this.addForm.community = "";
        //     this.addForm.communityCode = "";
        //     const res = await reqRegionLevel(val);
        //     this.communityList = res.data.rows;
        //     this.streetList.forEach((item) => {
        //         if (item.regionCode == val) {
        //             this.addForm.street = item.regionName;
        //             return;
        //         }
        //     });
        // },
        // // 社区名称赋值
        // changecommunity(val) {
        //     this.communityList.forEach((item) => {
        //         if (item.regionCode == val) {
        //             this.addForm.community = item.regionName;
        //             return;
        //         }
        //     });
        // },
        // // 省市区获取
        // async openMap() {
        //     // await  this.getLongitudeLatitude();
        //     this.isShowMap = true;
        //     this.innerVisible = true;
        // },
        // // 查询省级行政组织
        // async getRegion() {
        //     const res = await reqRegion();
        //     // console.log(res);
        //     res.data.rows.forEach((item) => {
        //         if (item.regionName == this.addForm.province) {
        //             this.addForm.provinceCode = item.regionCode; //省行政码
        //             return;
        //         }
        //     });
        //     this.getRegionLevel();
        // },
        // // 查询省级下行政组织
        // async getRegionLevel() {
        //     if (this.addForm.provinceCode == "") return;
        //     const res = await reqRegionLevel(this.addForm.provinceCode);
        //     this.cityList = res.data.rows;
        //     res.data.rows.forEach((item) => {
        //         if (item.regionName == this.addForm.city) {
        //             this.addForm.cityCode = item.regionCode; //市行政码
        //             return;
        //         }
        //     });
        //     // 特殊市辖区查不到  默认选择第一个
        //     if (this.addForm.cityCode == "") {
        //         this.addForm.city = res.data.rows[0].regionName;
        //         this.addForm.cityCode = res.data.rows[0].regionCode;
        //     }

        //     const res2 = await reqRegionLevel(this.addForm.cityCode);
        //     this.areaList = res2.data.rows;
        //     if (this.addForm.area == "") return; //地图中没获取到区级不走下面
        //     res2.data.rows.forEach((item) => {
        //         if (item.regionName == this.addForm.area) {
        //             this.addForm.areaCode = item.regionCode; //区行政码
        //             return;
        //         }
        //     });

        //     //   if (this.addForm.areaCode == "" || this.addForm.areaCode == null)
        //     //     return this.$modal.notifyWarning("数据异常，请联系管理员");
        //     const res3 = await reqRegionLevel(this.addForm.areaCode);
        //     this.streetList = res3.data.rows;
        //     if (this.addForm.street == "") return; //地图中没获取到街道不走下面
        //     res3.data.rows.forEach((item) => {
        //         if (item.regionName == this.addForm.street) {
        //             this.addForm.streetCode = item.regionCode; //街道行政码
        //             return;
        //         }
        //     });
        //     // console.log(this.addForm.streetCode);

        //     const res4 = await reqRegionLevel(this.addForm.streetCode);
        //     this.communityList = res4.data.rows;
        //     if (this.addForm.community == "") return;
        //     res4.data.rows.forEach((item) => {
        //         if (item.regionName == this.addForm.community) {
        //             this.addForm.communityCode = item.regionCode; //街道行政码
        //             return;
        //         }
        //     });
        // },
        // 点击新增
        submit() {
            this.$refs.refForm.validate(async (valid) => {
                if (!valid) return;
                let {
                    parentId,
                    type,
                    orgName,
                } = this.addForm;
                //   if (!streetCode) return this.$modal.notifyWarning("请选择地区");
                let params = {
                    parentId,
                    tenantId: this.user.tenantId,
                    orgName,
                    type,
                };
                // this.params.parentId = this.fixedPjtInfo.id;
                const res = await reqOrgAdd(params);
                if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                this.$modal.notifySuccess("新增成功");
                this.closeDialog();
                this.$parent.Region();
                //   this.$parent.loadChildren2(parentId);
            });
        },
        //地址转经纬度
        addrHand() {
            let that = this;
            // console.log(that.addForm.province+that.addForm.city+that.addForm.area+that.addForm.address);
            $.ajax({
                type: "get",
                dataType: "jsonp",
                data: {
                    key: "44FBZ-OVKKP-T23D5-VGHUE-XDXC3-BDF53", // 填申请到的腾讯key
                    address:
                        that.addForm.province +
                        that.addForm.city +
                        that.addForm.area +
                        that.addForm.street +
                        that.addForm.address, //具体的地址
                    output: "jsonp", //返回格式：支持JSON/JSONP，默认JSON
                },
                jsonp: "callback",
                jsonpCallback: "QQmap",
                url: "https://apis.map.qq.com/ws/geocoder/v1/?",
                success: function (json) {
                    // console.log(json)
                    if (json.status == 0) {
                        that.addForm.lng = json.result.location.lng;
                        that.addForm.lat = json.result.location.lat;
                        // console.log(that.addForm.lat);
                        // console.log(that.addForm.lng);
                        // that.$message({
                        //   message: '成功获取位置的经纬度',
                        //   type: 'success'
                        // })
                    } else {
                        // that.$message.error('获取该位置经纬度失败')
                    }
                },
                error: function (err) {
                    // that.$message.error('异常错误，请刷新浏览器后重试')
                },
            });
        },
        // 点击关闭弹框
        closeDialog() {
            // this.$parent.getorgFlag();
            this.dialogVisible = false;
            this.areaList = [];
            this.streetList = [];
            this.cityList = [];
            this.communityList = [];
            this.addForm = {
                parentId: "",
                tenantId: "",
                type: "",
                orgName: "",
            };
            this.$nextTick(() => {
                this.$refs.refForm.resetFields();
                this.$refs.refForm.clearValidate();
                this.$refs.refTreeSelSearch.resetFields();
            });
        },
        closeDialog2() {
            this.$nextTick(() => {
                this.$refs.refForm.resetFields();
            });
        },
    },

    deactivated() {
        if (this.$refs.refForm != null) {
            this.closeDialog();
        }
        this.innerVisible = false;
    },
};
</script>

<style lang="less" scoped>
@import url("../../../common.less");

.mapLoc {
    // height: 100vh;
    // width: 100vw;
    // position: fixed;
    // z-index: 9999;
    // top: 0;
    // left: 0;

    height: 60vh;
    width: 100%;
    overflow-y: hidden;

    .iframe {
        width: 100%;
        height: 100%;
    }
}

.zuobiao {
    color: @primaryTxtcolor;
}

// ::v-deep .el-textarea__inner {
//   color: #ececed !important;
// }
// 省市区/
::v-deep .el-input.is-disabled .el-input__inner {
    border-color: @primaryBorderColor !important;
}

// 折叠样式
.el_collapse {
    color: @primaryThemeTxtColor2;
}

::v-deep .el-collapse-item__header {
    // color: @primaryThemeTxtColor2;
    color: #7367f0 !important;
    width: 140px;
    height: 45px;
    line-height: 45px;
    font-size: 14px;
    // padding-left: 15px;
}

.el-collapse {
    border: none;
}

::v-deep .el-collapse-item__arrow {
    margin: 0;
}

::v-deep .el-collapse-item__content {
    padding-bottom: 0;
}

::v-deep .el-collapse-item__wrap {
    background: transparent;
}

// 折叠样式结束
.el-icon-question {
    margin-left: 10px;
    color: #7367f0;
    cursor: pointer;
    font-size: 20px;
}

// 省市区级联
// ::v-deep .el-cascader-node.in-active-path, .el-cascader-node.is-active, .el-cascader-node.is-selectable.in-checked-path{
//     color: #fff !important;
// }
::v-deep .el-cascader .el-cascader-node.is-selectable.in-active-path {
    color: #7367f0 !important;
}
</style>